package com.elinkway.infinitemovies.application;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;

import com.alibaba.sdk.android.feedback.impl.FeedbackAPI;
import com.androidquery.callback.AbstractAjaxCallback;
import com.apkfuns.logutils.LogUtils;
import com.baidu.mobads.AdView;
import com.baidu.mobads.BaiduManager;
import com.bestv.app.view.InitShellApplicationContextListener;
import com.bestv.app.view.VideoViewShell;
import com.elinkway.infinitemovies.bigdata.BigDataConfig;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.bigdata.BigDataLaunchQuitActionTask;
import com.elinkway.infinitemovies.bigdata.BigDataStats;
import com.elinkway.infinitemovies.bigdata.BigDataUtils;
import com.elinkway.infinitemovies.config.LogoImageLoader;
import com.elinkway.infinitemovies.dao.DBHelper;
import com.elinkway.infinitemovies.dao.DatabaseManager;
import com.elinkway.infinitemovies.dao.PreferencesManager;
import com.elinkway.infinitemovies.download.DownloadManager;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.service.DownloadService;
import com.elinkway.infinitemovies.stats.StatsHelper;
import com.elinkway.infinitemovies.ui.activity.NewMainActivity;
import com.elinkway.infinitemovies.ui.activity.SplashActivity;
import com.elinkway.infinitemovies.ui.activity.VideoDetailActivity;
import com.elinkway.infinitemovies.utils.CDEManager;
import com.elinkway.infinitemovies.utils.CvcHelperManager;
import com.elinkway.infinitemovies.utils.FadeInDisplayer;
import com.elinkway.infinitemovies.utils.IdUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.MoviesUtils;
import com.elinkway.infinitemovies.utils.PushUtil;
import com.elinkway.infinitemovies.utils.RequestAdDataHelper;
import com.elinkway.infinitemovies.utils.SSLSocketFactoryEx;
import com.elinkway.infinitemovies.utils.SharePreferenceManager;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.Utils;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.le123.ysdq.BuildConfig;
import com.le123.ysdq.R;
import com.letv.sdk.LetvPlayerSDK;
import com.lvideo.http.LVideoHttpConstant;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.novaplayer.LetvMediaPlayerManager;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.qqlive.mediaplayer.api.TVK_SDKMgr;
import com.tendcloud.tenddata.TCAgent;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.PlatformConfig;

import java.io.File;
import java.security.KeyStore;
import java.util.List;
import java.util.Stack;

import cn.jpush.android.api.JPushInterface;

public class MoviesApplication extends MultiDexApplication {

    private final static String TAG = "MoviesApplication";

    // 播放器APPKEY
    private final String PLAYER_APPKEY = "01012020301000100010";

    private final String APP_ID = "1";

    public static final String START_FROM_NOTIFICATION = "start_from_notification";

    public static final String YINGSHIDAQUAN_PACKAGENAME = BuildConfig.APPLICATION_ID;

    public static final String YINGSHIDAQUAN_PACKAGENAME_THREAD = BuildConfig.APPLICATION_ID + ":cde";

    private String VIEW_PAGER_POSITION = "ViewPagerPosition";

    public static String PLAY_VIDEO_THREAD = "com.elinkway.infinitemovies.ui.activity.play.PlayActivitySelfOwn";

    public static String VIDEO_DETAIL_THREAD = "com.elinkway.infinitemovies.ui.activity.VideoDetailActivity";

    public static String RANK_DETAIL_THREAD = "com.elinkway.infinitemovies.ui.activity.RankDetailActivity";

    public static String TOPIC_DETAIL_THREAD = "com.elinkway.infinitemovies.ui.activity.TopicDetailActivity";

    // 播放器PCODE
    public static final String PLAYER_PCODE = "010110698";

    public static boolean isSaveLogContinue = true;

    private static MoviesApplication instance;

    private static DisplayImageOptions defaultoptions;

     // 下载管理类
    private DownloadManager mDownloadManager;

    // 下载限速
    private boolean isSpeedCut = false;

    private Stack<Activity> activityStack;

    private RequestAdDataHelper mRequestAdDataHelper;

    public static boolean isLoginDone;    //是否刚登陆成功

    private Handler mHandler;

    private String runningActivityPackageName;

    private String runningActivityName;

    private Activity activity;

    private Activity secondActivity;

    private boolean isStartWebView;

    private static boolean isApplicationRunning;

    private String mLastPageClassName;

    private String mPgvLastPageId;

    private boolean isNeedReLocation;

    public boolean isFirstEnterApplication = true;

    private long mBackGroundTime = 0;
    private int mCount = 0;
    private boolean isBackGround = false;

    private CvcHelperManager mCvcHelperManager;

    public String getRunningActivityName() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        return activityManager.getRunningTasks(1).get(0).topActivity.getClassName();
    }

    public String getRunningPackageName() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        return activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
    }

    public void exitApplication(boolean isByUser) {
        isApplicationRunning = false;
        isFirstEnterApplication = true;
        Utils.setPublicIpAddress("");
        SharePreferenceManager.saveVaule(instance, SharePreferenceManager.EXIT_AD_ID, "");
        BigDataLaunchQuitActionTask quitStatsTask = new BigDataLaunchQuitActionTask();
        quitStatsTask.setAcode(BigDataConstants.ACODE_QUIT)
                .setApType(BigDataConstants.AP_QUIT_OFF)
                .setAR(BigDataConstants.AR_SUCCESS)
                .setNT(BigDataUtils.getNetType(this)).onEventStart();
        quitStatsTask.onEventStop(true);
        BigDataStats.post(quitStatsTask);
        BigDataStats.postEnvOnExit();
        LetvPlayerSDK.getInstance().onAppExit();
        for (int i = 0; i < activityStack.size(); i++) {
            Activity activity = activityStack.get(i);
            if (null != activity)
                activity.finish();
        }
        activityStack.clear();
        if (secondActivity != null) {
            secondActivity.finish();
            secondActivity = null;
        }
        if (activity != null) {
            activity.finish();
            activity = null;
        }
    }

    public Stack<Activity> getActivityStack() {
        return activityStack;
    }

    public void setActivityStack(Activity activity) {
        this.activityStack.add(activity);
    }

    public Activity getActivity() {
        if (null != activityStack) {
            for (int i = 0; i < activityStack.size(); i++) {
                if (activityStack.get(i) != null) {
                    return activityStack.get(i);
                }
            }
        }
        return null;
    }

    public void setTopActivity(Activity topActivity) {
        activity = topActivity;
    }

    public Activity getTopActivity() {
        return activity;
    }

    public void setVideoDetailActivity(Activity activity) {
        secondActivity = activity;
    }

    public Activity getVideoDetailActivity() {
        return secondActivity;
    }

    public void setIsStartWebView(boolean isStart) {
        isStartWebView = isStart;
    }

    public boolean getIsStartWebView() {
        return isStartWebView;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(this);
        LogUtils.getLogConfig()
                .configTagPrefix(BuildConfig.FLAVOR)
                .configAllowLog(BuildConfig.DEBUG);
        JPushInterface.setDebugMode(BuildConfig.DEBUG);
        JPushInterface.init(this);
        Fresco.initialize(this);
        //第二个参数是appkey，就是百川应用创建时候的appkey
        FeedbackAPI.initAnnoy(this, IdUtils.ALI_FEEDBACK_APP_ID);
        mHandler = new Handler();

        registerMyCallbacks();
        String processName = getProcessName(this, android.os.Process.myPid());
        if (processName != null) {
            boolean defaultProcess = processName.equals(this.getPackageName());
            if (defaultProcess) {
                instance = this;
                //TalkingData init
                TCAgent.LOG_ON = BuildConfig.DEBUG;
                TCAgent.init(this, IdUtils.TALKING_DATA_APP_ID, MoviesUtils.getClientChannel());
                TCAgent.setReportUncaughtExceptions(true);

                BaiduManager.init(this);
                AdView.setAppSid(this, IdUtils.AD_BAIDU_APP_ID);

                MobclickAgent.UMAnalyticsConfig umConfig = new MobclickAgent.UMAnalyticsConfig(this,
                        BuildConfig.UMENG_APP_KEY, MoviesUtils.getClientChannel());
                MobclickAgent.startWithConfigure(umConfig);

                UmengEventPoster.doEventPost(UmengEventPoster.OPENAPP);

                try {
                    AbstractAjaxCallback.setSSF(new SSLSocketFactoryEx(KeyStore.getInstance(KeyStore.getDefaultType())));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                LVideoHttpConstant.setDebug(MoviesConstant.DEBUG);

                PlatformConfig.setWeixin(IdUtils.WECHAT_APP_ID, IdUtils.WECHAT_APP_SECRET);
                //微信 appid appsecret
                PlatformConfig.setSinaWeibo(IdUtils.WEIBO_APP_ID, IdUtils.WEIBO_APP_SECRET);
                //新浪微博 appkey appsecret
                PlatformConfig.setQQZone(IdUtils.QQ_APP_ID, IdUtils.QQ_APP_SECRET);
                // QQ和Qzone appid appkey

                File cacheDir = StorageUtils
                        .getOwnCacheDirectory(getApplicationContext(), "WhatsLIVE/Cache");
                defaultoptions = new DisplayImageOptions.Builder()
                        .showImageOnLoading(R.drawable.default_bg_img_big)
                        // resource or drawable
                        .showImageForEmptyUri(R.drawable.default_bg_img_big)
                        // resource or drawable
                        .showImageOnFail(R.drawable.default_bg_img_big)
                        // resource or drawable
                        .resetViewBeforeLoading(false).cacheInMemory(true)
                        .cacheOnDisk(true).considerExifParams(false)
                        .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
                        .bitmapConfig(Bitmap.Config.RGB_565)
                        .displayer(new FadeInDisplayer(500, true, false, false))
                        .handler(new Handler()).build();
                ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                        getApplicationContext()).memoryCacheExtraOptions(720, 1280)
                        .threadPoolSize(3)
                        .threadPriority(Thread.NORM_PRIORITY - 1)
                        .tasksProcessingOrder(QueueProcessingType.FIFO)
                        .diskCacheFileCount(100)
                        .denyCacheImageMultipleSizesInMemory()
                        .memoryCache(new WeakMemoryCache())
                        .memoryCacheSizePercentage(10)
                        .diskCacheSize(60 * 1024 * 1024)
                        .diskCache(new UnlimitedDiscCache(cacheDir))
                        .defaultDisplayImageOptions(defaultoptions).build();
                DisplayImageOptions defaultLogoOptions = new DisplayImageOptions.Builder()
                        .resetViewBeforeLoading(true)
                        .cacheInMemory(true)
                        .imageScaleType(ImageScaleType.EXACTLY)
                        .cacheOnDisc(true)
                        .bitmapConfig(Bitmap.Config.ARGB_4444).build();
                ImageLoaderConfiguration LogoConfig = new ImageLoaderConfiguration.Builder(
                        getApplicationContext()).threadPoolSize(1)
                        .threadPriority(Thread.NORM_PRIORITY - 1)
                        .tasksProcessingOrder(QueueProcessingType.FIFO)
                        .denyCacheImageMultipleSizesInMemory()
                        .memoryCache(new WeakMemoryCache())
                        .diskCache(new UnlimitedDiscCache(cacheDir))
                        .defaultDisplayImageOptions(defaultLogoOptions).build();
                LogoImageLoader.getInstance().init(LogoConfig);
                ImageLoader.getInstance().init(config);

                DatabaseManager.initializeInstance(new DBHelper(getApplicationContext()));
                mDownloadManager = new DownloadManager(this);

                mRequestAdDataHelper = new RequestAdDataHelper(this);

                activityStack = new Stack<Activity>();
                BigDataConfig bigdataconfig = new BigDataConfig();
                bigdataconfig.setChannel(MoviesUtils.getClientChannel())
                        .setP1(IdUtils.BIGDATA_P1).setP2(IdUtils.BIGDATA_P2).setP3(IdUtils.BIGDATA_P3);
                BigDataStats.init(this, bigdataconfig);
                // 创建系统文件夹，用于android4.4后，sd卡下载
                File file = getExternalFilesDir(android.os.Environment.DIRECTORY_MOVIES);

                // 初始化CDEManager 启动CDE
                CDEManager cdeManager = CDEManager.getInstance(instance);
                cdeManager.startCde();

                mCvcHelperManager = CvcHelperManager.getInstance();
                mCvcHelperManager.startCvcHelperService();
                LogUtils.e("!!!!!!!!!MoviesApplication!!!!!!!!!!!!!!");
                if (!SharePreferenceManager.getVaule(this, SharePreferenceManager.SUBCHANNEL_POST_FLAG)
                        && !TextUtils.isEmpty(MoviesConstant.SUBCHANNEL)) {
                    StatsHelper.postSubChannel();
                }

                try {
                    RealmDaoManager.init(this);
                    // 初始化播放器模块
                    LetvMediaPlayerManager.getInstance().init(instance.getApplicationContext(),
                            PLAYER_APPKEY, APP_ID, PLAYER_PCODE, MoviesUtils.getClientVersionName());
                    // 初始化腾讯视频sdk
                    TVK_SDKMgr.setDebugEnable(false);
                    TVK_SDKMgr.initSdk(getApplicationContext(), IdUtils.TENCENT_TV_APP_KEY, "");
                    LetvPlayerSDK.getInstance().init(this.getApplicationContext(), true, cdeManager.getmCdeHelper());
                    // 初始化百事通sdk
                    VideoViewShell.InitShellApplicationContext(getApplicationContext(), bestSdkListener);
                } catch (Exception e) {
                    LogUtils.e(e.getMessage());
                }

            }
        }
    }

    private void registerMyCallbacks() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {
                mCount++;
                if (mCount == 1) {
                    //切到前台  lifecycle
                    if(isBackGround){
                        isBackGround = false;
                    }else{
                        return;
                    }
                    if(activity.getIntent()!=null && activity.getIntent().getBooleanExtra(START_FROM_NOTIFICATION, false)){
                        return;
                    }
                    LogUtils.i("fffff backup");
                    long timeGap = System.currentTimeMillis() - mBackGroundTime;
                    int splahInterval = PreferencesManager.getInstance().getSplashInterval();
                    if(splahInterval == -1){
                        return;
                    }
                    if(mBackGroundTime != 0 && timeGap > splahInterval*1000){
                        if(!SplashActivity.class.getName().equals(MoviesApplication.getInstance().getRunningActivityName())){
                            Intent intent = new Intent(activity, SplashActivity.class);
                            intent.setAction(Intent.ACTION_MAIN);
                            intent.addCategory(Intent.CATEGORY_LAUNCHER);
                            intent.putExtra("from", "back");
                            activity.startActivity(intent);
                        }
                    }
                }
            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {
                mCount--;
                if (mCount == 0) {
                    //切到后台  lifecycle
                    LogUtils.i("fffff background");
                    mBackGroundTime = System.currentTimeMillis();
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
//                if(!(activity instanceof NewMainActivity)){
//                    if(activity.getIntent()!=null && activity.getIntent().getBooleanExtra(START_FROM_NOTIFICATION, false)){
//                        Intent intent = new Intent(activity, NewMainActivity.class);
//                        activity.startActivity(intent);
//                    }
//                }
            }
        });
    }

    public InitShellApplicationContextListener bestSdkListener = new InitShellApplicationContextListener() {
        @Override
        public void onInitComplete() {

        }

        @Override
        public void onInitFailed() {

        }
    };

    public void judgeJump(Intent originIntent) {
        runningActivityPackageName = getRunningPackageName();
        runningActivityName = getRunningActivityName();
        Intent intent = MoviesApplication.this.getPackageManager().getLaunchIntentForPackage(MoviesApplication.this.getPackageName());
        intent.setPackage((String) null);
        intent.addFlags(268435456);
        intent.putExtra(START_FROM_NOTIFICATION, true);
        intent.putExtras(originIntent.getExtras());
        dealWithPushNotification(intent);
    }

    public static MoviesApplication getInstance() {
        return instance;
    }

    public DownloadManager getDownloadManager() {
        return mDownloadManager;
    }

    /**
     * 广告类
     *
     * @return
     */
    public RequestAdDataHelper getRequestAdDataHelper() {
        return mRequestAdDataHelper;
    }

    public boolean isSpeedCut() {
        return isSpeedCut;
    }

    public void setSpeedCut(boolean isSpeedCut) {
        this.isSpeedCut = isSpeedCut;
    }

    public void startCheckSDCardFreeSizeService() {
        Intent intent = new Intent(this, DownloadService.class);
        intent.setAction(DownloadService.CHECK_SDCARD_FREESIZE);
        startService(intent);
    }

    public String getURLFromLinkShell(String originalStr) {
        return originalStr;
    }

    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

    public void dealWithPushNotification(final Intent intent) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                PushUtil.doPush(intent);
            }
        });
    }

    public void startMainFromPushBack(Activity activity, String bottomIndex) {
        if(!(activity instanceof NewMainActivity)){
            if(activity.getIntent() != null && activity.getIntent().getBooleanExtra(START_FROM_NOTIFICATION, false)){
                Intent intent = new Intent(activity, NewMainActivity.class);
                intent.putExtra(PushUtil.EXTRA_PUSH_NOTIFICATION, bottomIndex);
                activity.startActivity(intent);
                if(!(activity instanceof VideoDetailActivity) && !activity.isFinishing()){
                    activity.finish();
                }
            }
        }
    }

    public void setIsRunning(boolean isRun) {
        isApplicationRunning = isRun;
    }

    public boolean isRunning() {
        return isApplicationRunning;
    }

    public class UmengReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            LogUtils.e("receive the intent ");
        }
    }

    public String getRunningActivityPackageName() {
        return runningActivityPackageName;
    }

    public void setRunningActivityPackageName(String runningActivityPackageName) {
        this.runningActivityPackageName = runningActivityPackageName;
    }

    public void setRunningActivityName(String runningActivityName) {
        this.runningActivityName = runningActivityName;
    }

    public void setLastPageClassName(String className) {
        mLastPageClassName = className;
    }

    public String getLastPageClassName() {
        return mLastPageClassName;
    }

    public String getmPgvLastPageId() {
        return mPgvLastPageId;
    }

    public void setmPgvLastPageId(String mPgvLastPageId) {
        this.mPgvLastPageId = mPgvLastPageId;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        CDEManager.getInstance(instance).stopCde();
    }

    public boolean isNeedReLocation() {
        return isNeedReLocation;
    }

    public void setNeedReLocation(boolean needReLocation) {
        isNeedReLocation = needReLocation;
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if(level == TRIM_MEMORY_UI_HIDDEN){
            isBackGround = true;
        }
    }

    public long getmBackGroundTime() {
        return mBackGroundTime;
    }

    public void setmBackGroundTime(long mBackGroundTime) {
        this.mBackGroundTime = mBackGroundTime;
    }
}
